import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import { Base64 } from 'js-base64'

const clientId = 'webapp'
const clientSecret = 'webapp123'

// create an axios instance
const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API,
    withCredentials: false,
    timeout: 10000
})

// request interceptor
service.interceptors.request.use(
    config => {
        if (store.getters.token) {
            config.headers['Authorization'] = 'Bearer ' + getToken()
        } else {
            config.headers['Authorization'] = 'Basic ' + Base64.encode(clientId + ':' + clientSecret)
        }
        return config
    },
    error => {
        console.log(error)
        return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
    response => {
        const res = response.data
        if (res.code && res.code !== 20000) {
            const msg = res.message || '系统异常请重试！'
            Message({
                message: msg,
                type: 'error',
                duration: 5 * 1000
            })
            return Promise.reject(new Error(msg || 'Error'))
        }
        return res
    },
    error => {
        console.log(error.response);
        if (error.response) {
            const res = error.response.data
            if (res.error && res.error === 'invalid_token') {
                MessageBox.confirm(res.error_description, '会话超时', {
                    confirmButtonText: '重新登陆',
                    type: 'warning'
                }).then(() => {
                    store.dispatch('user/resetToken').then(() => {
                        location.reload()
                    })
                })
            } else {
                Message({
                    message: res.message || '接口请求异常！',
                    type: 'error',
                    duration: 3 * 1000
                })
            }
        } else {
            Message({
                message: '网络异常!',
                type: 'error',
                duration: 5 * 1000
            })
        }
        return Promise.reject(error)
    }
)

export default service
